<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>HTTP</title>
  <link href="../Styles/stylesheet.css" rel="stylesheet" type="text/css" />
  <script src="../toc.js" type="text/javascript">



  //<![CDATA[

   <!-- empty -->
  //]]>
  </script>
  <script type="text/javascript">




  /* <![CDATA[ */
    (function() {
        var s = document.createElement("script"), t = document.getElementsByTagName("script")[0];
        s.type = "text/javascript";
        s.async = true;
        s.src = "http://api.flattr.com/js/0.6/load.js?mode=auto";
        t.parentNode.insertBefore(s, t);
    })();
  /* ]]> */
  </script>
  <style type="text/css">
/*<![CDATA[*/

  body { counter-reset: chapter 8; }

  span.sgc-7 {color: green}
  span.sgc-6 {color: darkmagenta}
  span.sgc-5 {color: black}
  span.sgc-4 {color: blue}
  span.sgc-3 {color: DarkRed}
  span.sgc-2 {color: purple}
  span.sgc-1 {color: firebrick}
  /*]]>*/
  </style>
</head>

<body>
  <div class="chapter">
    <h1 id="heading_id_2" class="en">HTTP</h1>
    <h1 id="heading_id_2" class="zh">关于HTTP</h1>
  </div>

  <div class="preface"></div>

  <div class="generate_from_h2" id="generated-toc"></div>

  <h2 id="heading_id_3" class="en">Introduction</h2>
  <h2 id="heading_id_3" class="zh">简介</h2>

  <p class="en">The World Wide Web is a major distributed system, with millions of users. A site may become a Web host by running an HTTP server. While Web clients are typically users with a browser, there are many other "user agents" such as web spiders, web application clients and so on.</p>
  <p class="cn">万维网是一个庞大的，拥有数以百万计用户的分布式系统。网站就是一个运行着HTTP服务器的Web主机。而Web客户端通常是浏览器用户，当然也还有许多其他的“用户”，如网络蜘蛛，Web应用程序客户端等。</p>

  <p class="en">The Web is built on top of the HTTP (Hyper-Text Transport Protocol) which is layered on top of TCP. HTTP has been through three publically available versions, but the latest - version 1.1 - is now the most commonly used.</p>
  <p class="zh">Web使用的HTTP（超文本传输协议）是基于TCP协议的。HTTP有三个公开可用的版本，目前最常用的是最新的版本1.1。</p>

  <p class="en">In this chapter we give an overview of HTTP, followed by the Go APIs to manage HTTP connections.</p>
  <p class="zh">本章首先对HTTP进行概述，然后介绍如何通过Go API管理HTTP连接。</p>

  <h2 id="heading_id_4" class="en">Overview of HTTP</h2>
  <h2 id="heading_id_4" class="zh">HTTP概述</h2>

  <h3 id="heading_id_5" class="en">URLs and resources</h3>
  <h3 id="heading_id_5" class="zh">URL和资源</h3>

  <p class="en" class="en">URLs specify the location of a <em>resource</em>. A resource is often a static file, such as an HTML document, an image, or a sound file. But increasingly, it may be a dynamically generated object, perhaps based on information stored in a database.</p>
  <p class="zh" class="zh">URL指定<em>资源</em>的位置。资源通常是HTML文档、图片、声音文件这样的静态文件，但越来越多的资源是动态生成的对象，比如根据数据库信息生成。</p>

  <p class="en">When a user agent requests a resource, what is returned is not the resource itself, but some <em>representation</em> of that resource. For example, if the resource is a static file, then what is sent to the user agent is a copy of the file.</p>
  <p class="zh">“用户”请求资源时，返回的并不是资源本身，而是资源的<em>代表</em>。如果资源是静态文件，那么返回给用户的就是文件的一个副本。</p>

  <p class="en">Multiple URLs may point to the same resource, and an HTTP server will return appropriate representations of the resource for each URL. For example, an company might make product information available both internally and externally using different URLs for the same product. The internal representation of the product might include information such as internal contact officers for the product, while the external representation might include the location of stores selling the product.</p>
  <p class="zh">不同的URL可以指向相同的资源，HTTP服务器会给每个URL返回适当的代表。例如，针对同一个产品，某公司可以使用不同的URL给本地和外地的用户查看其产品信息，本地用户可以看到本地产品联系人这类内容，而外地用户看到的内容则包括产品销售门店的地址等等。</p>

  <p class="en">This view of resources means that the HTTP protocol can be fairly simple and straightforward, while an HTTP server can be arbitrarily complex. HTTP has to deliver requests from user agents to servers and return a byte stream, while a server might have to do any amount of processing of the request.</p>
  <p class="zh">这其实就意味着，HTTP协议本身非常简单直接，但HTTP服务器却可能非常复杂。HTTP将用户请求发送到服务器，并返回字节流，而服务器针对该请求可能需要做很多很多处理。</p>

  <h3 id="heading_id_6" class="en">HTTP characteristics</h3>
  <h3 id="heading_id_6" class="zh">HTTP的特点</h3>

  <p class="en">HTTP is a stateless, connectionless, reliable protocol. In the simplest form, each request from a user agent is handled reliably and then the connection is broken. Each request involves a separate TCP connection, so if many reources are required (such as images embedded in an HTML page) then many TCP connections have to be set up and torn down in a short space of time.</p>
  <p class="zh">HTTP协议是无状态，面向连接和可靠的。最简单的形式是，每个从用户发起的请求被可靠地处理，然后断开连接。每次请求都包括一个独立的TCP连接，所以如果要请求很多资源（如在HTML页面中嵌入的图像），则必须在很短的时间内建立并断开许多TCP连接。</p>

  <p class="en">Thera are many optimisations in HTTP which add complexity to the simple structure, in order to create a more efficient and reliable protocol.</p>
  <p class="zh">为构建更高效更可靠的协议，有许多在这种简单结构基础上添加复杂性的优化技术。</p>

  <h3 id="heading_id_7" class="en">Versions</h3>
  <h3 id="heading_id_7" class="zh">版本</h3>

  <p class="en">There are 3 versions of HTTP</p>
  <p class="zh">HTTP有三个版本</p>

  <ul class="en">
    <li>Version 0.9 - totally obsolete</li>
    <li>Version 1.0 - almost obsolete</li>
    <li>Version 1.1 - current</li>
  </ul>
  <ul class="zh">
    <li>Version 0.9 - 完全废弃</li>
    <li>Version 1.0 - 基本废弃</li>
    <li>Version 1.1 - 当前版本</li>
  </ul>

  <p class="en">Each version must understand requests and responses of earlier versions.</p>
  <p class="zh">每个版本必须兼容早期的版本。</p>

  <h3 id="heading_id_8">HTTP 0.9</h3>

  <h4 id="heading_id_9" class="en">Request format</h4>
  <h4 id="heading_id_9" class="zh">请求格式</h4>
  <pre>
Request = Simple-Request

Simple-Request = "GET" SP Request-URI CRLF
  </pre>

  <h4 id="heading_id_10" class="en">Response format</h4>
  <h4 id="heading_id_10" class="zh">响应格式</h4>

  <p class="en">A response is of the form</p>
  <p class="zh">响应形式类似：</p>
  <pre>
Response = Simple-Response

Simple-Response = [Entity-Body]
  </pre>

  <h3 id="heading_id_11">HTTP 1.0</h3>

  <p class="en">This version added much more information to the requests and responses. Rather than "grow" the 0.9 format, it was just left alongside the new version.</p>
  <p class="zh">该版本在请求和响应中增加了很多信息。与其说是0.9的升级版，还不如说它是一个全新的版本。</p>

  <h4 id="heading_id_12" class="en">Request format</h4>
  <h4 id="heading_id_12" class="zh">请求格式</h4>

  <p class="en">The format of requests from client to server is</p>
  <p class="zh">从客户端到服务器端的请求格式：</p>
  <pre>
Request = Simple-Request | Full-Request

Simple-Request = "GET" SP Request-URI CRLF

Full-Request = Request-Line
                *(General-Header
                | Request-Header
                | Entity-Header)
                CRLF
                [Entity-Body]
</pre>

  <p class="en">A Simple-Request is an HTTP/0.9 request and must be replied to by a Simple-Response.</p>
  <p class="zh">简单请求(Simple-Request)表明是一个 HTTP/0.9 请求，必须回复简单响应(Simple-Response)。</p>

  <p class="en">A Request-Line has format</p>
  <p class="zh">请求行(Request-Line)的格式如下：</p>
  <pre>
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
</pre>

  <p class="en">where</p>
  <p class="zh">其中</p>
  <pre>
Method = "GET" | "HEAD" | POST |
         extension-method
</pre>

  <p class="en">e.g.</p>
  <p class="zh">如：</p>
  <pre>
GET http://jan.newmarch.name/index.html HTTP/1.0
</pre>

  <h4 id="heading_id_13" class="en">Response format</h4>
  <h4 id="heading_id_13" class="zh">响应格式</h4>

  <p>A response is of the form</p>
  <p>响应的形式如下：</p>
  <pre>
Response = Simple-Response | Full-Response

Simple-Response = [Entity-Body]

Full-Response = Status-Line
                *(General-Header
                | Response-Header
                | Entity-Header)
                CRLF
                [Entity-Body]
</pre>

  <p class="en">The Status-Line gives information about the fate of the request:</p>
  <p class="zh">状态行(Status-Line)会给出请求的最后的状态信息:</p>
  <pre>
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
</pre>

  <p class="en">e.g.</p>
  <p class="zh">如</p>
  <pre>
HTTP/1.0 200 OK
</pre>

  <p class="en">The codes are</p>
  <p class="zh">状态码：</p>
  <pre>
Status-Code =     "200" ; OK
                | "201" ; Created
                | "202" ; Accepted
                | "204" ; No Content
                | "301" ; Moved permanently
                | "302" ; Moved temporarily
                | "304" ; Not modified
                | "400" ; Bad request
                | "401" ; Unauthorised
                | "403" ; Forbidden
                | "404" ; Not found
                | "500" ; Internal server error
                | "501" ; Not implemented
                | "502" ; Bad gateway
                | "503" | Service unavailable
                | extension-code
</pre>

  <p class="en">The Entity-Header contains useful information about the Entity-Body to follow</p>
  <p class="zh">实体头(Entity-Header)包含了有关实体(Entity-Body)的有用信息</p>
  <pre>
Entity-Header = Allow
                | Content-Encoding
                | Content-Length
                | Content-Type
                | Expires
                | Last-Modified
                | extension-header
</pre>

  <p class="en">For example</p>
  <p class="zh">例如：</p>
  <pre>
HTTP/1.1 200 OK
Date: Fri, 29 Aug 2003 00:59:56 GMT
Server: Apache/2.0.40 (Unix)
Accept-Ranges: bytes
Content-Length: 1595
Connection: close
Content-Type: text/html; charset=ISO-8859-1
</pre>

  <h3 id="heading_id_14">HTTP 1.1</h3>

  <p class="en">HTTP 1.1 fixes many problems with HTTP 1.0, but is more complex because of it. This version is done by extending or refining the options available to HTTP 1.0. e.g.</p>
  <p class="zh">HTTP 1.1 修复了 HTTP 1.0 中的很多问题，因此更加复杂。例如此版本中扩展和完善了HTTP 1.0中的可选项。</p>

  <ul class="en">
    <li>there are more commands such as TRACE and CONNECT</li>
    <li>you should use absolute URLs, particularly for connecting by proxies e.g
      <pre><code>
      GET http://www.w3.org/index.html HTTP/1.1
      </code></pre>
    </li>
    <li>there are more attributes such as If-Modified-Since, also for use by proxies</li>
  </ul>
  <ul class="zh">
    <li>增加了命令，如 TRACE 和 CONNECT</li>
    <li>注意在通过代理服务器进行连接时，应当使用绝对路径。如：
      <pre><code>
      GET http://www.w3.org/index.html HTTP/1.1
      </code></pre>
    </li>
    <li>增加了更多属性，例如针对代理服务器的If-Modified-Since。</li>
  </ul>

  <p class="en">The changes include</p>
  <p class="zh">这些变动包括：</p>

  <ul class="en">
    <li>hostname identification (allows virtual hosts)</li>
    <li class="en">content negotiation (multiple languages)</li>
    <li class="en">persistent connections (reduces TCP overheads - this is very messy)</li>
    <li class="en">chunked transfers</li>
    <li class="en">byte ranges (request parts of documents)</li>
    <li class="en">proxy support</li>
  </ul>
  <ul class="zh">
    <li class="zh">主机名识别(支持虚拟主机)</li>
    <li class="zh">内容协商(多语言)</li>
    <li class="zh">持久连接(降低TCP开销)</li>
    <li class="zh">分块传送</li>
    <li class="zh">字节范围(请求文件部分内容)</li>
    <li class="zh">代理支持</li>
  </ul>

  <p class="en">The 0.9 protocol took one page. The 1.0 protocol was described in about 20 pages. 1.1 takes 120 pages.</p>
  <p class="zh">0.9版本的协议只有一页，1.0版本用了大约20页来说明，而1.1则用了120页。</p>

  <h2 id="heading_id_15" class="en">Simple user-agents</h2>
  <h2 id="heading_id_15" class="zh">简单用户代理(Simple user-agents)</h2>

  <p class="en">User agents such as browsers make requests and get responses. The response type is</p>
  <p class="zh">用户代理(User agent)(例如浏览器)用来发起请求和接收响应。代码中的 response type 如下：</p>
  <pre><code>
type Response struct {
    Status     string // e.g. "200 OK"
    StatusCode int    // e.g. 200
    Proto      string // e.g. "HTTP/1.0"
    ProtoMajor int    // e.g. 1
    ProtoMinor int    // e.g. 0

    RequestMethod string // e.g. "HEAD", "CONNECT", "GET", etc.

    Header map[string]string

    Body io.ReadCloser

    ContentLength int64

    TransferEncoding []string

    Close bool

    Trailer map[string]string
}
    </code></pre>

  <p class="en">We shall examine this data structure through examples. The simplest request is from a user agent is "HEAD" which asks for information about a resource and its HTTP server. The function</p>
  <p class="zh">通过实例可以了解其数据结构。最简单的请求是由用户代理发起"HEAD"命令，其中包括请求的资源和HTTP服务器。函数</p>
  <pre><code>
func Head(url string) (r *Response, err os.Error)
    </code></pre>

  <p class="en">can be used to make this query.</p>
  <p class="zh">可用来发起此请求。</p>

  <p class="en">The status of the response is in the response field <code>Status</code>, while the field <code>Header</code> is a map of the header fields in the HTTP response. A program to make this request and display the results is</p>
  <p class="zh">响应状态对应response中的<code>Status</code>属性，而<code>Header</code>属性对应HTTP响应的header域。下面的程序用来发起请求和显示结果：</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* Head
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 2 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"host:port"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        url := os.<span class="sgc-4">Args</span>[1]

        response, err := http.<span class="sgc-4">Head</span>(url)
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(2)
        }

        fmt.<span class="sgc-4">Println</span>(response.<span class="sgc-4">Status</span>)
        <span class="sgc-2">for</span> k, v := range response.<span class="sgc-4">Header</span> {
                fmt.<span class="sgc-4">Println</span>(k+<span class="sgc-3">":"</span>, v)
        }

        os.<span class="sgc-4">Exit</span>(0)
}
</span></code></pre>

  <p class="en">When run against a resource as in <code>Head http://www.golang.com/</code> it prints something like</p>
  <p class="zh">程序运行请求资源，<code>Head http://www.golang.com/</code>，输出结果类似：</p>
  <pre><code>
200 OK
Content-Type: text/html; charset=utf-8
Date: Tue, 14 Sep 2010 05:34:29 GMT
Cache-Control: public, max-age=3600
Expires: Tue, 14 Sep 2010 06:34:29 GMT
Server: Google Frontend
    </code></pre>

  <p class="en">Usually, we are want to retrieve a resource rather than just get information about it. The "GET" request will do this, and this can be done using</p>
  <p class="zh">通常我们希望接收到一个资源内容而不是其有关信息。"GET"请求就是做来做这个的，使用如下函数即可：</p>
  <pre><code>
func Get(url string) (r *Response, finalURL string, err os.Error)
    </code></pre>

  <p class="en">The content of the response is in the response field <code>Body</code> which is of type <code>io.ReadCloser</code>. We can print the content to the screen with the following program</p>
  <p class="zh">响应内容为response的<code>Body</code>属性。它是一个<code>io.ReadCloser</code>类型。我们可以用以下程序在屏幕上打印相应内容</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* Get
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"net/http/httputil"</span>
        <span class="sgc-3">"os"</span>
        <span class="sgc-3">"strings"</span>
)

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 2 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"host:port"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        url := os.<span class="sgc-4">Args</span>[1]

        response, err := http.<span class="sgc-4">Get</span>(url)
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(2)
        }

        <span class="sgc-2">if</span> response.<span class="sgc-4">Status</span> != <span class="sgc-3">"200 OK"</span> {
                fmt.<span class="sgc-4">Println</span>(response.<span class="sgc-4">Status</span>)
                os.<span class="sgc-4">Exit</span>(2)
        }

        b, <span class="sgc-6">_</span> := httputil.<span class="sgc-4">DumpResponse</span>(response, false)
        fmt.<span class="sgc-4">Print</span>(string(b))

        contentTypes := response.<span class="sgc-4">Header</span>[<span class="sgc-3">"Content-Type"</span>]
        <span class="sgc-2">if</span> !acceptableCharset(contentTypes) {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Cannot handle"</span>, contentTypes)
                os.<span class="sgc-4">Exit</span>(4)
        }

        <span class="sgc-2">var</span> buf [512]<span class="sgc-7">byte</span>
        reader := response.<span class="sgc-4">Body</span>
        <span class="sgc-2">for</span> {
                n, err := reader.<span class="sgc-4">Read</span>(buf[0:])
                <span class="sgc-2">if</span> err != nil {
                        os.<span class="sgc-4">Exit</span>(0)
                }
                fmt.<span class="sgc-4">Print</span>(string(buf[0:n]))
        }
        os.<span class="sgc-4">Exit</span>(0)
}

<span class="sgc-2">func</span> acceptableCharset(contentTypes []string) bool {
        <span class="sgc-1">// each type is like [text/html; charset=UTF-8]</span>
        <span class="sgc-1">// we want the UTF-8 only</span>
        <span class="sgc-2">for</span> <span class="sgc-6">_</span>, cType := range contentTypes {
                <span class="sgc-2">if</span> strings.<span class="sgc-4">Index</span>(cType, <span class="sgc-3">"UTF-8"</span>) != -1 {
                        <span class="sgc-2">return</span> true
                }
        }
        <span class="sgc-2">return</span> false
}
</span></code></pre>

  <p class="en">Note that there are important character set issues of the type discussed in the previous chapter. The server will deliver the content using some character set encoding, and possibly some transfer encoding. Usually this is a matter of negotiation between user agent and server, but the simple <code>Get</code> command that we are using does not include the user agent component of the negotiation. So the server can send whatever character encoding it wishes.</p>
  <p class="zh">注意这里有一个重要的字符集类型问题，在前面章节也讨论过。服务器提供内容时使用的字符集编码，甚至传输编码，通常是用户代理和服务器之间协商的那结果，但我们使用的<code>Get</code>的命令很简单，它不包括用户代理的内容协商组件。因此，服务器可以自行决定使用什么字符编码。</p>

  <p class="en">At the time of first writing, I was in China. When I tried this program on <code>www.google.com</code>, Google's server tried to be helpful by guessing my location and sending me the text in the Chinese character set Big5! How to tell the server what character encoding is okay for me is discussed later.</p>
  <p class="zh">我第一次写的时候是在中国。当我用这个程序访问<code>www.google.com</code>时，谷歌的服务器尝试猜测我的地理位置，然后很厉害地使用了Big5码给我发送文本！后面会讨论如何告知服务器给我什么字符编码最好。</p>

  <h2 id="heading_id_16" class="en">Configuring HTTP requests</h2>
  <h2 id="heading_id_16" class="zh">设置HTTP请求</h2>

  <p class="en">Go also supplies a lower-level interface for user agents to communicate with HTTP servers. As you might expect, not only does it give you more control over the client requests, but requires you to spend more effort in building the requests. However, there is only a small increase.</p>
  <p class="zh">Go还提供一个较低级别的用户代理接口用来与HTTP服务器进行通信。你可能已经想到，这样可以更灵活地控制客户端请求，当然创建请求也会更费力气。不过这只需要多费一点点力气。</p>


  <p class="en">The data type used to build requests is the type <code>Request</code>. This is a complex type, and is given in the Go documentation as</p>
  <p class="zh">用来创建请求的数据类型是<code>Request</code>。这是个复杂的类型，Go语言文档中给出的定义如下：</p>
  <pre><code>
type Request struct {
    Method     string // GET, POST, PUT, etc.
    RawURL     string // The raw URL given in the request.
    URL        *URL   // Parsed URL.
    Proto      string // "HTTP/1.0"
    ProtoMajor int    // 1
    ProtoMinor int    // 0


    // A header maps request lines to their values.
    // If the header says
    //
    //  accept-encoding: gzip, deflate
    //  Accept-Language: en-us
    //  Connection: keep-alive
    //
    // then
    //
    //  Header = map[string]string{
    //          "Accept-Encoding": "gzip, deflate",
    //          "Accept-Language": "en-us",
    //          "Connection": "keep-alive",
    //  }
    //
    // HTTP defines that header names are case-insensitive.
    // The request parser implements this by canonicalizing the
    // name, making the first character and any characters
    // following a hyphen uppercase and the rest lowercase.
    Header map[string]string

    // The message body.
    Body io.ReadCloser

    // ContentLength records the length of the associated content.
    // The value -1 indicates that the length is unknown.
    // Values &gt;= 0 indicate that the given number of bytes may be read from Body.
    ContentLength int64

    // TransferEncoding lists the transfer encodings from outermost to innermost.
    // An empty list denotes the "identity" encoding.
    TransferEncoding []string

    // Whether to close the connection after replying to this request.
    Close bool

    // The host on which the URL is sought.
    // Per RFC 2616, this is either the value of the Host: header
    // or the host name given in the URL itself.
    Host string

    // The referring URL, if sent in the request.
    //
    // Referer is misspelled as in the request itself,
    // a mistake from the earliest days of HTTP.
    // This value can also be fetched from the Header map
    // as Header["Referer"]; the benefit of making it
    // available as a structure field is that the compiler
    // can diagnose programs that use the alternate
    // (correct English) spelling req.Referrer but cannot
    // diagnose programs that use Header["Referrer"].
    Referer string

    // The User-Agent: header string, if sent in the request.
    UserAgent string

    // The parsed form. Only available after ParseForm is called.
    Form map[string][]string

    // Trailer maps trailer keys to values.  Like for Header, if the
    // response has multiple trailer lines with the same key, they will be
    // concatenated, delimited by commas.
    Trailer map[string]string
}
    </code></pre>

  <p class="en">There is a lot of information that can be stored in a request. You do not need to fill in all fields, only those of interest. The simplest way to create a request with default values is by for example</p>
  <p class="zh">请求中可以存放大量的信息，但你不需要填写所有的内容，只填必要的即可。最简单的使用默认值创建请求的方法如下：</p>
  <pre>
    <code>
request, err := http.NewRequest("GET", url.String(), nil)
    </code>
  </pre>

  <p class="en">Once a request has been created, you can modify fields. For example, to specify that you only wish to receive UTF-8, add an "Accept-Charset" field to a request by</p>
  <p class="zh">请求创建后，可以修改其内容字段(field)。比如，需指定只接受UTF-8，可添加一个"Accept-Charset"字段：</p>
  <pre>
    <code>
request.Header.Add("Accept-Charset", "UTF-8;q=1, ISO-8859-1;q=0")
    </code>
  </pre>

  <p class="en">(Note that the default set ISO-8859-1 always gets a value of one unless mentioned explicitly in the list.).</p>
  <p class="zh">(注意，若没有在列表中提及，则默认设置ISO-8859-1总是返回值1).</p>

  <p class="en">A client setting a charset request is simple by the above. But there is some confusion about what happens with the server's return value of a charset. The returned resource <em>should</em> have a <code>Content-Type</code> which will specify the media type of the content such as <code>text/html</code>. If appropriate the media type should state the charset, such as <code>text/html; charset=UTF-8</code>. If there is no charset specification, then according to the HTTP specification it should be treated as the default ISO8859-1 charset. But the HTML 4 specification states that since many servers don't conform to this, then you can't make any assumptions.</p>
  <p class="zh">如上所述，客户端设置字符集请求很简单。但对于服务器返回的字符集，发生的事情就比较复杂。返回的资源<em>理应</em>包含<code>Content-Type</code>，用来指明内容的媒介类型，如：<code>text/html</code>。有些媒介类型应当声明字符集，如<code>text/html; charset=UTF-8</code>。如果没有指明字符集，按照HTTP规范就应当作为默认的ISO8859-1字符集处理。但是很多服务器并不符合此约定，因此HTML 4规定此时不能做任何假设。</p>

  <p class="en">If there is a charset specified in the server's <code>Content-Type</code>, then assume it is correct. if there is none specified, since 50% of pages are in UTF-8 and 20% are in ASCII then it is safe to assume UTF-8. Only 30% of pages may be wrong :-(.</p>
  <p class="zh">如果服务器的<code>Content-Type</code>指定了字符集，那么就认为它是正确的。如果未指定字符集，由于50%的页面是UTF-8的，20%的页面是ASCII的，因此假设字符集是UTF-8的会比较安全，但仍然有30%的页面可能会出错:-(。</p>

  <h2 id="heading_id_17" class="en">The Client object</h2>
  <h2 id="heading_id_17" class="zh">客户端对象</h2>

  <p class="en">To send a request to a server and get a reply, the convenience object <code>Client</code> is the easiest way. This object can manage multiple requests and will look after issues such as whether the server keeps the TCP connection alive, and so on.</p>
  <p class="zh">向服务器发送一个请求并取得回复，最简单的方法是使用方便对象<code>Client</code>。此对象可以管理多个请求，并处理一些问题，如与服务器间的TCP连接是否保持活动状态等。</p>

  <p class="en">This is illustrated in the following program</p>
  <p class="zh">下面的程序给出了示例：</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* ClientGet
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"net/url"</span>
        <span class="sgc-3">"os"</span>
        <span class="sgc-3">"strings"</span>
)

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 2 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"http://host:port/page"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        url, err := url.<span class="sgc-4">Parse</span>(os.<span class="sgc-4">Args</span>[1])
        checkError(err)

        client := &amp;http.<span class="sgc-4">Client</span>{}

        request, err := http.<span class="sgc-4">NewRequest</span>(<span class="sgc-3">"GET"</span>, url.<span class="sgc-4">String</span>(), nil)
        <span class="sgc-1">// only accept UTF-8
</span> request.<span class="sgc-4">Header</span>.<span class="sgc-4">Add</span>(<span class="sgc-3">"Accept-Charset"</span>, <span class="sgc-3">"UTF-8;q=1, ISO-8859-1;q=0"</span>)
        checkError(err)

        response, err := client.<span class="sgc-4">Do</span>(request)
        <span class="sgc-2">if</span> response.<span class="sgc-4">Status</span> != <span class="sgc-3">"200 OK"</span> {
                fmt.<span class="sgc-4">Println</span>(response.<span class="sgc-4">Status</span>)
                os.<span class="sgc-4">Exit</span>(2)
        }

        chSet := getCharset(response)
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"got charset %s\n"</span>, chSet)
        <span class="sgc-2">if</span> chSet != <span class="sgc-3">"UTF-8"</span> {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Cannot handle"</span>, chSet)
                os.<span class="sgc-4">Exit</span>(4)
        }

        <span class="sgc-2">var</span> buf [512]<span class="sgc-7">byte</span>
        reader := response.<span class="sgc-4">Body</span>
        fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"got body"</span>)
        <span class="sgc-2">for</span> {
                n, err := reader.<span class="sgc-4">Read</span>(buf[0:])
                <span class="sgc-2">if</span> err != nil {
                        os.<span class="sgc-4">Exit</span>(0)
                }
                fmt.<span class="sgc-4">Print</span>(string(buf[0:n]))
        }

        os.<span class="sgc-4">Exit</span>(0)
}

<span class="sgc-2">func</span> getCharset(response *http.<span class="sgc-4">Response</span>) string {
        contentType := response.<span class="sgc-4">Header</span>.<span class="sgc-4">Get</span>(<span class="sgc-3">"Content-Type"</span>)
        <span class="sgc-2">if</span> contentType == <span class="sgc-3">""</span> {
                <span class="sgc-1">// guess
</span>         <span class="sgc-2">return</span> <span class="sgc-3">"UTF-8"</span>
        }
        idx := strings.<span class="sgc-4">Index</span>(contentType, <span class="sgc-3">"charset:"</span>)
        <span class="sgc-2">if</span> idx == -1 {
                <span class="sgc-1">// guess
</span>         <span class="sgc-2">return</span> <span class="sgc-3">"UTF-8"</span>
        }
        <span class="sgc-2">return</span> strings.<span class="sgc-4">Trim</span>(contentType[idx:], <span class="sgc-3">" "</span>)
}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <h2 id="heading_id_18" class="en">Proxy handling</h2>
  <h2 id="heading_id_18" class="zh">代理处理</h2>

  <h3 id="heading_id_19" class="en">Simple proxy</h3>
  <h3 id="heading_id_19" class="zh">简单代理</h3>

  <p class="en">HTTP 1.1 laid out how HTTP should work through a proxy. A "GET" request should be made to a proxy. However, the URL requested should be the full URL of the destination. In addition the HTTP header should contain a "Host" field, set to the proxy. As long as the proxy is configured to pass such requests through, then that is all that needs to be done.</p>
  <p class="zh">HTTP 1.1规定了HTTP应当如何通过代理工作。向代理服务器发送一个"GET"请求。但是请求URL必须是完整的目标地址。此外，设置代理的HTTP头应当包括"Host"字段。只要代理服务器设置为允许这样的请求通过，那么做这些就够了。</p>

  <p class="en">Go considers this to be part of the HTTP transport layer. To manage this it has a class <code>Transport</code>. This contains a field which can be set to a <em>function</em> that returns a URL for a proxy. If we have a URL as a string for the proxy, the appropriate transport object is created and then given to a client object by</p>
  <p class="zh">Go把这看成HTTP传输层的一部分。可使用<code>Transport</code>类进行管理。可以使用<em>函数</em>将代理服务器的URL返回到它的一个字段。假设有一个代理服务器地址字符串URL，相应的创建Transport对象并交给Client对象的代码就是：</p>
  <pre>
    <code>
proxyURL, err := url.Parse(proxyString)
transport := &amp;http.Transport{Proxy: http.ProxyURL(proxyURL)}
client := &amp;http.Client{Transport: transport}
    </code>
  </pre>

  <p class="en">The client can then continue as before.</p>
  <p class="zh">客户端可以像之前一样继续使用</p>

  <p class="en">The following program illustrates this:</p>
  <p class="zh">下面是程序范例:</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* ProxyGet
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"io"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"net/http/httputil"</span>
        <span class="sgc-3">"net/url"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 3 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"http://proxy-host:port http://host:port/page"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        proxyString := os.<span class="sgc-4">Args</span>[1]
        proxyURL, err := url.<span class="sgc-4">Parse</span>(proxyString)
        checkError(err)
        rawURL := os.<span class="sgc-4">Args</span>[2]
        url, err := url.<span class="sgc-4">Parse</span>(rawURL)
        checkError(err)

        transport := &amp;http.<span class="sgc-4">Transport</span>{<span class="sgc-4">Proxy</span>: http.<span class="sgc-4">ProxyURL</span>(proxyURL)}
        client := &amp;http.<span class="sgc-4">Client</span>{<span class="sgc-4">Transport</span>: transport}

        request, err := http.<span class="sgc-4">NewRequest</span>(<span class="sgc-3">"GET"</span>, url.<span class="sgc-4">String</span>(), nil)

        dump, <span class="sgc-6">_</span> := httputil.<span class="sgc-4">DumpRequest</span>(request, false)
        fmt.<span class="sgc-4">Println</span>(string(dump))

        response, err := client.<span class="sgc-4">Do</span>(request)

        checkError(err)
        fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Read ok"</span>)

        <span class="sgc-2">if</span> response.<span class="sgc-4">Status</span> != <span class="sgc-3">"200 OK"</span> {
                fmt.<span class="sgc-4">Println</span>(response.<span class="sgc-4">Status</span>)
                os.<span class="sgc-4">Exit</span>(2)
        }
        fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Reponse ok"</span>)

        <span class="sgc-2">var</span> buf [512]<span class="sgc-7">byte</span>
        reader := response.<span class="sgc-4">Body</span>
        <span class="sgc-2">for</span> {
                n, err := reader.<span class="sgc-4">Read</span>(buf[0:])
                <span class="sgc-2">if</span> err != nil {
                        os.<span class="sgc-4">Exit</span>(0)
                }
                fmt.<span class="sgc-4">Print</span>(string(buf[0:n]))
        }

        os.<span class="sgc-4">Exit</span>(0)
}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                <span class="sgc-2">if</span> err == io.<span class="sgc-4">EOF</span> {
                        <span class="sgc-2">return</span>
                }
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <p class="en">If you have a proxy at, say, XYZ.com on port 8080, test this by</p>
  <p class="zh">假设有一个代理服务器XYZ.com，端口8080，测试命令就是</p>
  <pre>
    <code>
go run ProxyGet.go http://XYZ.com:8080/ http://www.google.com
    </code>
  </pre>

  <p class="en">If you don't have a suitable proxy to test this, then download and install the Squid proxy to your own computer.</p>
  <p class="zh">如果没有合适的代理服务器可供测试，也可以在自己的计算机上下载安装Squid proxy。</p>

  <p class="en">The above program used a known proxy passed as an argument to the program. There are many ways in which proxies can be made known to applications. Most browsers have a configuration menu in which you can enter proxy information: such information is not available to a Go application. Some applications may get proxy information from an <code>autoproxy.pac</code> file somewhere in your network: Go does not (yet) know how to parse these JavaScript files and so cannot use them. Linux systems using Gnome have a configuration system called <code>gconf</code> in which proxy information can be stored: Go cannot access this. <em>But</em> it can find proxy information if it is set in operating system environment variables such as HTTP_PROXY or http_proxy using the function</p>
  <p class="zh">上面的程序是将已知的代理服务器地址作为参数传入的。有很多办法可以将代理服务器的地址通知到应用程序。大多数浏览器可以通过配置菜单输入代理服务器的信息：但这些信息对Go应用没有用。有些应用程序可以从网络中某处找到<code>autoproxy.pac</code>文件取得其中的代理服务器信息，但Go(目前还)不能解析JavaScript文件，因此也不能使用。Gnome Linux系统使用的配置系统<code>gconf</code>里可以存储代理服务器信息，但Go也访问不了。<em>但是</em>，如果在操作系统环境变量中设置代理服务器信息（如HTTP_PROXY或http_proxy），Go可以通过以下函数访问到：</p>
  <pre>
    <code>
func ProxyFromEnvironment(req *Request) (*url.URL, error)
    </code>
  </pre>

  <p class="en">If your programs are running in such an environment you can use this function instead of having to explicitly know the proxy parameters.</p>
  <p class="zh">假如你的程序运行在这样的环境中，就可以使用此功能，而不用明确指定代理服务器参数。</p>

  <h3 id="heading_id_20" class="en">Authenticating proxy</h3>
  <h3 id="heading_id_20" class="zh">身份验证代理</h3>

  <p class="en">Some proxies will require authentication, by a user name and password in order to pass requests. A common scheme is "basic authentication" in which the user name and password are concatenated into a string "user:password" and then BASE64 encoded. This is then given to the proxy by the HTTP request header "Proxy-Authorisation" with the flag that it is the basic authentication</p>
  <p class="zh">有些代理服务器要求通过用户名和密码进行身份验证才能传递请求。一般的方法是“基本身份验证”：将用户名和密码串联成一个字符串“user:password”，然后进行Base64编码，然后添加到HTTP请求头的“Proxy-Authorization”中，再发送到代理服务器</p>

  <p class="en">The following program illlustrates this, adding the Proxy-Authentication header to the previous proxy program:</p>
  <p class="zh">在前一个程序的基础上增加Proxy-Authorization头，示例如下：</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* ProxyAuthGet
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"encoding/base64"</span>
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"io"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"net/http/httputil"</span>
        <span class="sgc-3">"net/url"</span>
        <span class="sgc-3">"os"</span>
)

const auth = <span class="sgc-3">"jannewmarch:mypassword"</span>

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 3 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"http://proxy-host:port http://host:port/page"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        proxy := os.<span class="sgc-4">Args</span>[1]
        proxyURL, err := url.<span class="sgc-4">Parse</span>(proxy)
        checkError(err)
        rawURL := os.<span class="sgc-4">Args</span>[2]
        url, err := url.<span class="sgc-4">Parse</span>(rawURL)
        checkError(err)

        <span class="sgc-1">// encode the auth
</span> basic := <span class="sgc-3">"Basic "</span> + base64.<span class="sgc-4">StdEncoding</span>.<span class="sgc-4">EncodeToString</span>([]<span class="sgc-7">byte</span>(auth))

        transport := &amp;http.<span class="sgc-4">Transport</span>{<span class="sgc-4">Proxy</span>: http.<span class="sgc-4">ProxyURL</span>(proxyURL)}
        client := &amp;http.<span class="sgc-4">Client</span>{<span class="sgc-4">Transport</span>: transport}

        request, err := http.<span class="sgc-4">NewRequest</span>(<span class="sgc-3">"GET"</span>, url.<span class="sgc-4">String</span>(), nil)

        request.<span class="sgc-4">Header</span>.<span class="sgc-4">Add</span>(<span class="sgc-3">"Proxy-Authorization"</span>, basic)
        dump, <span class="sgc-6">_</span> := httputil.<span class="sgc-4">DumpRequest</span>(request, false)
        fmt.<span class="sgc-4">Println</span>(string(dump))

        <span class="sgc-1">// send the request
</span> response, err := client.<span class="sgc-4">Do</span>(request)

        checkError(err)
        fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Read ok"</span>)

        <span class="sgc-2">if</span> response.<span class="sgc-4">Status</span> != <span class="sgc-3">"200 OK"</span> {
                fmt.<span class="sgc-4">Println</span>(response.<span class="sgc-4">Status</span>)
                os.<span class="sgc-4">Exit</span>(2)
        }
        fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Reponse ok"</span>)

        <span class="sgc-2">var</span> buf [512]<span class="sgc-7">byte</span>
        reader := response.<span class="sgc-4">Body</span>
        <span class="sgc-2">for</span> {
                n, err := reader.<span class="sgc-4">Read</span>(buf[0:])
                <span class="sgc-2">if</span> err != nil {
                        os.<span class="sgc-4">Exit</span>(0)
                }
                fmt.<span class="sgc-4">Print</span>(string(buf[0:n]))
        }

        os.<span class="sgc-4">Exit</span>(0)
}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                <span class="sgc-2">if</span> err == io.<span class="sgc-4">EOF</span> {
                        <span class="sgc-2">return</span>
                }
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <h2 id="heading_id_21" class="en">HTTPS connections by clients</h2>
  <h2 id="heading_id_21" class="zh">客户端发起HTTPS连接</h2>

  <p class="en">For secure, encrypted connections, HTTP uses TLS which is described in the chapter on security. The protocol of HTTP+TLS is called HTTPS and uses https:// urls instead of http:// urls.</p>
  <p class="zh">为保证连接的安全和加密，HTTP使用其在安全性章节中说明的TLS技术。HTTP+TLS的协议被称为HTTPS，它使用https://地址，而不是http://地址。</p>

  <p class="en">Servers are required to return valid X.509 certificates before a client will accept data from them. If the certificate is valid, then Go handles everything under the hood and the clients given previously run okay with https URLs.</p>
  <p class="zh">服务器必须在客户端接受从其数据前返回有效的X.509证书。如果证书有效，Go会在内部处理好所有的事情，而客户端会在使用HTTPS地址是和以前工作得一样出色。</p>

  <p class="en">Many sites have invalid certificates. They may have expired, they may be self-signed instead of by a recognised Certificate Authority or they may just have errors (such as having an incorrect server name). Browsers such as Firefox put a big warning notice with a "Get me out of here!" button, but you can carry on at your risk - which many people do.</p>
  <p class="zh">许多网站都使用无效的证书。这些证书可能已经过期，或者是自行签名的，而没有让认可的证书颁发机构签名；又或者他们可能只是用错了（比如服务器名称不对）。浏览器（如Firefox），会显示一个很大的警告通知，通知上放着“立即离开！”按钮，但你也可以仍然继续此风险 - 很多人会这么做。</p>

  <p class="en">Go presently bails out when it encounters certificate errors. There is cautious support for carrying on but I haven't got it working yet. So there is no current example for "carrying on in the face of adversity :-)". Maybe later.</p>
  <p class="zh">Go目前在遇到证书错误时，会bails out。对继续工作的支持非常谨慎，我还没有找到正确的方法。因此，目前也没有“继续此风险”任何示例 :-)。以后再说吧。</p>

  <h2 id="heading_id_22" class="en">Servers</h2>
  <h2 id="heading_id_22" class="zh">服务器</h2>

  <p class="en">The other side to building a client is a Web server handling HTTP requests. The simplest - and earliest - servers just returned copies of files. However, any URL can now trigger an arbitrary computation in current servers.</p>
  <p class="zh">这边创建客户端，另一边Web服务器则需要处理HTTP请求。最早最简单的服务器只是返回文件的副本。然而，目前的服务器上，随便一个URL都可能触发任何计算。</p>

  <h3 id="heading_id_23" class="en">File server</h3>
  <h3 id="heading_id_23" class="zh">文件服务器</h3>

  <p class="en">We start with a basic file server. Go supplies a <code>multi-plexer</code>, that is, an object that will read and interpret requests. It hands out requests to <code>handlers</code> which run in their own thread. Thus much of the work of reading HTTP requests, decoding them and branching to suitable functions in their own thread is done for us.</p>
  <p class="zh">我们从一个基本的文件服务器开始。Go提供了一个<code>multi-plexer</code>，即一个读取和解释请求的对象。它把请求交给运行在自己线程中的<code>handlers</code>。这样，许多读取HTTP请求，解码并转移到合适功能上的工作都可以在各自的线程中进行。</p>

  <p class="en">For a file server, Go also gives a <code>FileServer</code> object which knows how to deliver files from the local file system. It takes a "root" directory which is the top of a file tree in the local system, and a pattern to match URLs against. The simplest pattern is "/" which is the top of any URL. This will match all URLs.</p>
  <p class="zh">对于文件服务器，Go也提供了一个<code>FileServer</code>对象，它知道如何发布本地文件系统中的文件。它需要一个“root”目录，该目录是在本地系统中文件树的顶端；还有一个针对URL的匹配模式。最简单的模式是“/”，这是所有URL的顶部，可以匹配所有的URL。</p>

  <p class="en">An HTTP server delivering files from the local file system is almost embarrassingly trivial given these objects. It is</p>
  <p class="zh">HTTP服务器从本地文件系统中发布文件太简单了，让人都有点不好意思举例。如下：</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* File Server
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">func</span> main() {
        <span class="sgc-1">// deliver files from the directory /var/www</span>
        <span class="sgc-1">// fileServer := http.FileServer(http.Dir("/var/www"))</span>
        fileServer := http.<span class="sgc-4">FileServer</span>(http.<span class="sgc-4">Dir</span>(<span class="sgc-3">"/home/httpd/html/"</span>))

        <span class="sgc-1">// register the handler and deliver requests to it</span>
        err := http.<span class="sgc-4">ListenAndServe</span>(<span class="sgc-3">":8000"</span>, fileServer)
        checkError(err)
        <span class="sgc-1">// That's it!
</span>}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <p class="en">This server even delivers "404 not found" messages for requests for file resources that don't exist!</p>
  <p class="zh">甚至当请求到一个不存在的文件资源时，这个服务器还提供了“404未找到”的信息！</p>

  <h3 id="heading_id_24" class="en">Handler functions</h3>
  <h3 id="heading_id_24" class="zh">处理函数(Handler function)</h3>

  <p class="en">In this last program, the handler was given in the second argument to <code>ListenAndServe</code>. Any number of handlers can be registered first by calls to <code>Handle</code> or <code>handleFunc</code>, with signatures</p>
  <p class="zh">上一个程序中，handler被作为第二个参数传给<code>ListenAndServe</code>。可以先注册任意多个handler供<code>Handle</code>或<code>handleFunc</code>使用。调用方式：</p>
  <pre><code>
func Handle(pattern string, handler Handler)
func HandleFunc(pattern string, handler func(*Conn, *Request))
    </code></pre>

  <p class="en">The second argument to <code>HandleAndServe</code> could be <code>nil</code>, and then calls are dispatched to all registered handlers. Each handler should have a different URL pattern. For example, the file handler might have URL pattern "/" while a function handler might have URL pattern "/cgi-bin". A more specific pattern takes precedence over a more general pattern.</p>
  <p class="zh"><code>HandleAndServe</code>的第二个参数是可以是<code>nil</code>，调用会被分派到所有已注册的handler。每个对立对象都有不同的URL匹配模式。例如，可能文件handler的URL匹配模式是"/"，而一个函数handler的URL匹配模式是"/cgi-bin"。这里具体的模式优先级高于一般的模式。</p>

  <p class="en">Common CGI programs are <code>test-cgi</code> (written in the shell) or <code>printenv</code> (written in Perl) which print the values of the environment variables. A handler can be written to work in a similar manner.</p>
  <p class="zh">常见的CGI程序有<code>test-cgi</code>(shell程序)或<code>printenv</code>(Perl程序)用来打印环境变量的值。可以让handler用类似的方式工作。</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* Print Env
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/http"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">func</span> main() {
        <span class="sgc-1">// file handler for most files</span>
        fileServer := http.<span class="sgc-4">FileServer</span>(http.<span class="sgc-4">Dir</span>(<span class="sgc-3">"/var/www"</span>))
        http.<span class="sgc-4">Handle</span>(<span class="sgc-3">"/"</span>, fileServer)

        <span class="sgc-1">// function handler for /cgi-bin/printenv</span>
        http.<span class="sgc-4">HandleFunc</span>(<span class="sgc-3">"/cgi-bin/printenv"</span>, printEnv)

        <span class="sgc-1">// deliver requests to the handlers</span>
        err := http.<span class="sgc-4">ListenAndServe</span>(<span class="sgc-3">":8000"</span>, nil)
        checkError(err)
        <span class="sgc-1">// That's it!
</span>}

<span class="sgc-2">func</span> printEnv(writer http.<span class="sgc-4">ResponseWriter</span>, req *http.<span class="sgc-4">Request</span>) {
        env := os.<span class="sgc-4">Environ</span>()
        writer.<span class="sgc-4">Write</span>([]<span class="sgc-7">byte</span>(<span class="sgc-3">"&lt;h1&gt;Environment&lt;/h1&gt;\n&lt;pre&gt;"</span>))
        <span class="sgc-2">for</span> <span class="sgc-6">_</span>, v := range env {
                writer.<span class="sgc-4">Write</span>([]<span class="sgc-7">byte</span>(v + <span class="sgc-3">"\n"</span>))
        }
        writer.<span class="sgc-4">Write</span>([]<span class="sgc-7">byte</span>(<span class="sgc-3">"&lt;/pre&gt;"</span>))
}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <p class="en"><em>Note: for simplicity this program does not deliver well-formed HTML. It is missing html, head and body tags</em>.</p>
  <p class="zh"><em>注：为简单起见，本程序不提供完整的的HTML。这里缺少html、head和body标签。</em></p>

  <p class="en">Using the <code>cgi-bin</code> directory in this program is a bit cheeky: it doesn't call an external program like CGI scripts do. It just calls a Go function. Go does have the ability to call external programs using <code>os.ForkExec</code>, but does not yet have support for dynamically linkable modules like Apache's <code>mod_perl</code></p>
  <p class="zh">这个程序在使用<code>cgi-bin</code>目录时有点耍赖。其实它并没有调用外部的CGI脚本程序，而只是使用了一个Go的内部函数。Go确实可以通过<code>os.ForkExec</code>调用外部的程序，但还不能支持像Apache的<code>mod_perl</code>这样的动态连接库</p>

  <h3 id="heading_id_25" class="en">Bypassing the default multiplexer</h3>
  <h3 id="heading_id_25" class="zh">绕过默认的multiplexer</h3>

  <p class="en">HTTP requests received by a Go server are usually handled by a multiplexer the examines the path in the HTTP request and calls the appropriate file handler, etc. You can define your own handlers. These can either be registered with the default multiplexer by calling <code>http.HandleFunc</code> which takes a pattern and a function. The functions such as <code>ListenAndServe</code> then take a <code>nil</code> handler function. This was done in the last example.</p>
  <p class="zh">Go服务器接收到的HTTP请求通常是由一个multiplexer进行处理，检查HTTP请求的路径，然后调用合适的文件handler等等。你也可以定义自己的handler。将一个匹配模式参数和一个函数作为参数，调用<code>http.HandleFunc</code>，可以将其注册为默认的multiplexer。像<code>ListenAndServe</code>这样的函数就可以使用<code>nil</code>作为handler function。上一个例子就是这样做的。</p>

  <p class="en">If you want to take over the multiplexer role then you can give a non-zero function as the handler function. This function will then be totally responsible for managing the requests and responses.</p>
  <p class="zh">如果你想扮演multiplexer的角色，那么你就可以给一个非零函数作为handler function。这个函数将会全权负责管理请求和响应。</p>

  <p class="en">The following example is trivial, but illustrates the use of this: the multiplexer function simply returns a "204 No content" for <em>all</em> requests:</p>
  <p class="zh">下面的例子非常简单，但它说明了如何使multiplexer对<em>所有</em>请求都只返回一个“204 No content”：</p>
  <pre><code><span class="sgc-5">
<span class="sgc-1">/* ServerHandler
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"net/http"</span>
)

<span class="sgc-2">func</span> main() {

        myHandler := http.<span class="sgc-4">HandlerFunc</span>(<span class="sgc-2">func</span>(rw http.<span class="sgc-4">ResponseWriter</span>, request *http.<span class="sgc-4">Request</span>) {
                <span class="sgc-1">// Just return no content - arbitrary headers can be set, arbitrary body</span>
                rw.<span class="sgc-4">WriteHeader</span>(http.<span class="sgc-4">StatusNoContent</span>)
        })

        http.<span class="sgc-4">ListenAndServe</span>(<span class="sgc-3">":8080"</span>, myHandler)
}
</span></code></pre>

<p class="en">Arbitrarily complex behaviour can be built, of course.</p>
<p class="zh">当然，也可以把它做成无所不能的。</p>

<!--
<h2> Low-level servers </h2>
<p>
  Go also supplies a lower-level interface for servers. Again, this
  means that as the programmer you have to do more work.
  You first make a TCP server, and then wrap a <code>ServerConn</code>
  around it. Then you read <code>Request</code>'s and write
  <code>Response</code>'s.
</p>

<h3> Basic server </h3>
<p>
  The simplest response is to return a "204 No Content".
  The following server reads requests and dumps them to standard
  output while returning a 204. More complex handling could be done:
  [an error occurred while processing this directive]

<h2> Conclusion </h2>
<p>
Go has extensive support for HTTP. This is not surprising, since Go
was partly invented to fill a need by Google for their own servers.
</p>

<p>
Copyright Jan Newmarch, jan@newmarch.name
</p>
<p>If you like this book, please contribute using Flattr
<a class="FlattrButton" style="display:none;"
href="http://jan.newmarch.name/go/index.html"></a>
<br/> or donate using PayPal
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="encrypted" value="=====BEGIN PKCS7=====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=====END PKCS7=====
">
<input type="image" src="https://www.paypalobjects.com/WEBSCR-640-20110401-1/en_AU/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/WEBSCR-640-20110401-1/en_AU/i/scr/pixel.gif" width="1" height="1">
</form>
-->

</body>
</html>
